package cc.chenwenxi.iot;

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cc.chenwenxi.sdk.rainbow.FanKit;
import cc.chenwenxi.sdk.rainbow.LedKit;
import cc.chenwenxi.sdk.rainbow.OledKit;
import cc.chenwenxi.sdk.rainbow.PiKit;
import cc.chenwenxi.sdk.rainbow.RgbKit;
import cc.chenwenxi.sdk.rainbow.RgbKit.Rgb;
import cc.chenwenxi.tts.TtsBaiduKit;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import kits.iot.client.IotClient;
import kits.iot.client.entity.DriverInfo;
import kits.iot.client.entity.MqttInfo;
import kits.iot.pi.entity.PiIotMsg;
import kits.iot.pi.entity.PiIotMsg.BuzzerIot;
import kits.iot.pi.entity.PiIotMsg.FanIot;
import kits.iot.pi.entity.PiIotMsg.LedIot;
import kits.iot.pi.entity.PiIotMsg.OledIot;
import kits.iot.pi.entity.PiIotMsg.OledIot.OledType;
import kits.iot.pi.entity.PiIotMsg.RgbIot;
import kits.iot.pi.entity.PiIotMsg.TtsSay;
import kits.iot.pi.entity.PiIotMsg.Type;
import kits.my.QueueKit;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class PiIotMqtt {
	private @NonNull String topic;
	private @NonNull DriverInfo driverInfo;
	public static final QueueKit<PiIotMsg> queue = new QueueKit<>(1000);

	public void connect() throws Exception {
		IotClient iotClient = new IotClient(driverInfo);
		MqttInfo mqtt = iotClient.getMqtt();
		MqttClient client = iotClient.getMqtt(mqtt);

		log.info("订阅:{}", topic);
		client.subscribe(topic, new IMqttMessageListener() {
			@Override
			public void messageArrived(String topic, MqttMessage message) throws Exception {
				try {
					PiIotMsg msg = JSONObject.parseObject(message.toString(), PiIotMsg.class);
					log.info("加入队列,iot接收:{}", msg);
//					queue.offer(msg);
					iotMsg(msg);
				} catch (Exception e) {
					log.info("异常", e);
				}
			}
		});
	}
	
	//@Scheduled(fixedDelay = 200)
	public void mq() {
		Optional.of(queue).map(QueueKit::poll).ifPresent(msg -> {
			log.info("===发现队列:"+msg);
			this.iotMsg(msg);
		});
	}
	
	@Synchronized
	private void iotMsg(PiIotMsg msg) {
		Type type = msg.getType();
		if (type == Type.oled) {
			OledIot oled = msg.getOled();
			OledKit oledKit = new OledKit(Convert.toInt(oled.getX(), 0), Convert.toInt(oled.getY(), 0));
			if (!oled.getOn_off()) {
				oledKit.shutdown();
				return;
			}
			if (oled.getType() == OledType.text) {
				List<String> contents = oled.getContents();
				contents.add(DateUtil.formatTime(msg.getTime()));
				oledKit.text(contents);
			} else if (oled.getType() == OledType.pic) {

			}
		} else if (type == Type.buzzer) {
			BuzzerIot buzzer = msg.getBuzzer();
			if (buzzer.getOn_off()) {
				PiKit.buzzer.high();
			} else {
				PiKit.buzzer.low();
			}
		} else if (type == Type.fan) {
			FanIot fan = msg.getFan();
			new FanKit().speed(fan.getSeepd());
		} else if (type == Type.led) {
			List<LedIot> leds = msg.getLeds();
			new LedKit();
		} else if (type == Type.rgb) {
			RgbIot rgb = msg.getRgb();
			RgbKit rgbKit = new RgbKit();
			if (rgb.getOn_off()) {
				Rgb rgb2 = new RgbKit.Rgb(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
				rgbKit.setRgb(rgb2);
			} else {
				rgbKit.shutdown();
			}
		} else if (type == Type.tts) {
			TtsSay say = msg.getSay();
			BufferedInputStream input = new TtsBaiduKit(say.getSay()).getInput();
			try {
				Player player = new Player(input);
				player.play();
			} catch (JavaLayerException e) {
				log.error("播放语音异常", e);
			}
		}
	}

	public static void main(String[] args) throws Exception {
		String deviceName = "wQjJWpKLYLKanQ7x4aYS";
		String productKey = "a1CGXPQ9VHt";
		String secret = "wW5bAK5BpZSGcmY7FUs9YscURrRQFzz5";
		DriverInfo driverInfo = new DriverInfo().setDeviceName(deviceName).setProductKey(productKey).setDeviceSecret(secret);

		String topic = StrFormatter.format("/{}/{}/user/get", driverInfo.getProductKey(), driverInfo.getDeviceName());
		new PiIotMqtt(topic, driverInfo).connect();
	}
}
